package com.example.sprintboot.service.impl;

import com.example.sprintboot.entity.UserAddress;
import com.example.sprintboot.mapper.UserAddressMapper;
import com.example.sprintboot.service.UserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserAddressServiceImpl implements UserAddressService {
    
    @Autowired
    private UserAddressMapper userAddressMapper;
    
    @Override
    public List<UserAddress> getUserAddresses(Integer userId) {
        if (userId == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        return userAddressMapper.selectByUserId(userId);
    }
    
    @Override
    public UserAddress getAddressById(Integer addressId, Integer userId) {
        if (addressId == null || userId == null) {
            throw new RuntimeException("地址ID和用户ID不能为空");
        }
        
        UserAddress address = userAddressMapper.selectByAddressIdAndUserId(addressId, userId);
        if (address == null) {
            throw new RuntimeException("地址不存在或无权限访问");
        }
        return address;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserAddress addAddress(UserAddress address) {
        // 数据验证
        validateAddress(address);
        
        // 设置用户ID
        if (address.getUserId() == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        
        // 如果是第一个地址，设置为默认地址
        int addressCount = userAddressMapper.countByUserId(address.getUserId());
        if (addressCount == 0) {
            address.setIsDefault(1);
        } else if (address.getIsDefault() == null) {
            address.setIsDefault(0);
        }
        
        // 如果设置为默认地址，先取消其他默认地址
        if (address.getIsDefault() == 1) {
            userAddressMapper.cancelOtherDefaultAddress(address.getUserId(), null);
        }
        
        // 插入地址
        userAddressMapper.insert(address);
        return address;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserAddress updateAddress(UserAddress address) {
        // 数据验证
        validateAddress(address);
        
        // 检查地址是否存在且属于当前用户
        UserAddress existingAddress = getAddressById(address.getAddressId(), address.getUserId());
        
        // 如果设置为默认地址，先取消其他默认地址
        if (address.getIsDefault() == 1) {
            userAddressMapper.cancelOtherDefaultAddress(address.getUserId(), address.getAddressId());
        }
        
        // 更新地址
        userAddressMapper.updateById(address);
        return address;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAddress(Integer addressId, Integer userId) {
        if (addressId == null || userId == null) {
            throw new RuntimeException("地址ID和用户ID不能为空");
        }
        
        // 检查地址是否存在且属于当前用户
        UserAddress address = getAddressById(addressId, userId);
        
        // 如果是默认地址，不允许删除
        if (address.getIsDefault() == 1) {
            throw new RuntimeException("默认地址不能删除，请先设置其他地址为默认地址");
        }
        
        // 删除地址
        userAddressMapper.deleteById(addressId);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDefaultAddress(Integer addressId, Integer userId) {
        if (addressId == null || userId == null) {
            throw new RuntimeException("地址ID和用户ID不能为空");
        }
        
        // 检查地址是否存在且属于当前用户
        getAddressById(addressId, userId);
        
        // 取消其他默认地址
        userAddressMapper.cancelOtherDefaultAddress(userId, addressId);
        
        // 设置当前地址为默认地址
        userAddressMapper.setDefaultAddress(addressId);
    }
    
    @Override
    public UserAddress getDefaultAddress(Integer userId) {
        if (userId == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        return userAddressMapper.selectDefaultAddress(userId);
    }
    
    @Override
    public int getAddressCount(Integer userId) {
        if (userId == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        return userAddressMapper.countByUserId(userId);
    }
    
    /**
     * 验证地址信息
     */
    private void validateAddress(UserAddress address) {
        if (address == null) {
            throw new RuntimeException("地址信息不能为空");
        }
        
        if (!StringUtils.hasText(address.getReceiverName())) {
            throw new RuntimeException("收货人姓名不能为空");
        }
        
        if (!StringUtils.hasText(address.getPhone())) {
            throw new RuntimeException("手机号不能为空");
        }
        
        // 简单的手机号格式验证
        if (!address.getPhone().matches("^1[3-9]\\d{9}$")) {
            throw new RuntimeException("手机号格式不正确");
        }
        
        if (!StringUtils.hasText(address.getDetailAddress())) {
            throw new RuntimeException("详细地址不能为空");
        }
        
        // 限制地址长度
        if (address.getDetailAddress().length() > 300) {
            throw new RuntimeException("详细地址长度不能超过300个字符");
        }
    }
} 